package com.irdstudio.efp.esb.service.impl.sed.tax;

import java.util.List;
import java.util.Optional;

import com.irdstudio.basic.framework.core.util.TraceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.esb.common.client.resp.EsbRespRetInfBean;
import com.irdstudio.efp.esb.common.client.resp.EsbRespServiceBean;
import com.irdstudio.efp.esb.service.bo.req.sed.tax.ReqSedTaxInfoQueryBean;
import com.irdstudio.efp.esb.service.bo.resp.sed.tax.RespSedTaxInfoQueryBean;
import com.irdstudio.efp.esb.service.client.ESBClientFactory;
import com.irdstudio.efp.esb.service.facade.sed.tax.SedTaxInfoQueryService;

@Service("sedTaxInfoQueryService")
public class SedTaxInfoQueryServiceImpl implements SedTaxInfoQueryService {
	
	private static Logger logger = LoggerFactory.getLogger(SedTaxInfoQueryServiceImpl.class);

	@Override
	public RespSedTaxInfoQueryBean queryTaxInfo(ReqSedTaxInfoQueryBean reqSedTaxInfoQueryBean) throws Exception {
		logger.info("======>实时涉税信息查询接口【"+ TraceUtil.getTraceId() +"_50130003_01】开始<======");
		// 连接ESB请求实时查询税局信息接口
		RespSedTaxInfoQueryBean respSedTaxInfoQueryBean = new RespSedTaxInfoQueryBean();// 实时查询税局信息响应信息
		try {
			// 接收实时查询税局信息接口响应信息
			 EsbRespServiceBean esbRespServiceBean = ESBClientFactory.buildClient()
					.withBody(reqSedTaxInfoQueryBean)
					.withTradeNo(ESBConstant.TRADE_CODE_50130003)
					.withScene(ESBConstant.SCENE_NO_01)
					.create()
					.sendAndReceive();
			 if(esbRespServiceBean == null) {
				 throw new ESBException("请求ESB发生异常，请检查请求内容是否正确或者确认ESB是否连通");
			 }
			 
			Optional.ofNullable(esbRespServiceBean).orElseThrow(() -> new ESBException("访问ESB发生异常，请检查请求参数是否正确或ESB是否连通"));

			// 处理开放平台返回信息
			List<EsbRespRetInfBean> retInfArry = esbRespServiceBean.getSysHead().getRetInfArry();
			if(!"000000".equals(retInfArry.get(0).getRetCd())) {
				throw new  ESBException("开放平台发生异常，返回信息为" + retInfArry.toString());
			} else {
				//接收查询的信息（如果遇到格式有误的数据直接抛异常）
				respSedTaxInfoQueryBean = esbRespServiceBean.getBody(RespSedTaxInfoQueryBean.class);
			}
			logger.info("调用实时查询税局信息接口结束，返回信息：" + JSONObject.toJSONString(respSedTaxInfoQueryBean));
		} catch (ESBException e) {
			logger.error("调用实时查询税局信息接口出现异常：" + e.getMessage());
			throw new ESBException("调用实时查询税局信息接口出现异常：" + e.getMessage());
		} catch (NumberFormatException e) {
			logger.error("调用实时查询税局信息接口出现异常：涉及金额的数据未按金额数据（double）格式传入");
			throw new BizException("调用实时查询税局信息接口出现异常：涉及金额的数据未按金额数据（double）格式传入");
		}finally {
			logger.info("======>实时涉税信息查询接口【"+ TraceUtil.getTraceId() +"_50130003_01】开始<======");
		}
		return respSedTaxInfoQueryBean;
	}

}
